//
// Created by HJ on 2024-08-24.
//

#include "XArray.h"

bool XArray::Init(JNIEnv *env) {
    env_ = env;
    cla_ = env_->FindClass("java/util/ArrayList");
    get_ = env->GetMethodID(cla_,"get","(I)Ljava/lang/Object;");
    size_ = env->GetMethodID(cla_,"size","()I");

    init_ = env_->GetMethodID(cla_,"<init>","()V");
    add_ = env_->GetMethodID(cla_,"add","(Ljava/lang/Object;)Z");
    return false;
}

std::vector<std::string> XArray::ToVS(jobject arr) {
    std::vector<std::string> re;
    int len = env_->CallIntMethod(arr,size_);
    for(int i =0; i < len; i++){
        //获取jstring引用
        auto arr_str = (jstring)env_->CallObjectMethod(arr,get_,i);
        //转换为const char*
        auto c_str = env_->GetStringUTFChars(arr_str,nullptr);

        //存入vector
        re.push_back(c_str);

        //释放资源
        env_->ReleaseStringUTFChars(arr_str,c_str);//释放c_str
        env_->DeleteLocalRef(arr_str);
    }
    return re;
}

jobject XArray::ToArrayList(std::vector<std::string> vs) {
    //创建ArrayList 对象

    auto re = env_->NewObject(cla_,init_);
    for(auto &s:vs){
        auto str = env_->NewStringUTF(s.c_str());
        env_->CallBooleanMethod(re,add_,str);//插入数据到ArrayList 对象
        env_->DeleteLocalRef(str);
    }

    return re;
}


